package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.constant.Role;
import team.bluepen.supermarket.data.entity.User;
import team.bluepen.supermarket.util.UserChecker;
import team.bluepen.supermarket.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 注册控制
 * @author Kai
 */
@WebServlet(name = "RegisterControlServlet", urlPatterns = "/api/register-control")
public class RegisterControlServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User()
                .setUsername(username)
                .setPassword(password)
                .setRole(Role.USER)
                .build();
        Error checkState = UserChecker.checkUser(user);
        if (!checkState.getState()) {
            resp.sendRedirect("/register.jsp?error="+ checkState.getValue());
        }
        Error error = userRepository.createUser(user);
        resp.sendRedirect("/register.jsp?error="+ error.getValue());
    }
}
